<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Redis分布式锁 | Kylin</title><meta name="keywords" content="Redis,分布式锁"><meta name="author" content="Kylin"><meta name="copyright" content="Kylin"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="环境搭建properties123456789101112server.port&#x3D;1111spring.redis.database&#x3D;0spring.redis.host&#x3D;192.168.56.10spring.redis.port&#x3D;6379#连接池最大连接数（使用负值表示没有限制）默认8spring.redis.lettuce.pool.max-active&#x3D;8#连接池最大阻塞等待时间（使用负值">
<meta property="og:type" content="article">
<meta property="og:title" content="Redis分布式锁">
<meta property="og:url" content="https://www.codekylin.cn/64631.html">
<meta property="og:site_name" content="Kylin">
<meta property="og:description" content="环境搭建properties123456789101112server.port&#x3D;1111spring.redis.database&#x3D;0spring.redis.host&#x3D;192.168.56.10spring.redis.port&#x3D;6379#连接池最大连接数（使用负值表示没有限制）默认8spring.redis.lettuce.pool.max-active&#x3D;8#连接池最大阻塞等待时间（使用负值">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://qiniu.codekylin.cn/github/img/img/wallhaven-5wqmj8.jpg">
<meta property="article:published_time" content="2022-01-02T05:25:53.000Z">
<meta property="article:modified_time" content="2022-07-12T11:42:50.018Z">
<meta property="article:author" content="Kylin">
<meta property="article:tag" content="Redis">
<meta property="article:tag" content="分布式锁">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://qiniu.codekylin.cn/github/img/img/wallhaven-5wqmj8.jpg"><link rel="shortcut icon" href="https://qiniu.codekylin.cn/img/20200807181548.png"><link rel="canonical" href="https://www.codekylin.cn/64631"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//www.google-analytics.com" crossorigin=""/><link rel="preconnect" href="//hm.baidu.com"/><link rel="preconnect" href="//fonts.googleapis.com" crossorigin=""/><meta name="google-site-verification" content="gzeyWstt6NoTZKh7YFYNLNziL8HIZ8YH2Ug7xTDX5-Y"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.css" media="print" onload="this.media='all'"><script>var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "https://hm.baidu.com/hm.js?f76c34daefe747deee7c7be3ead2ba80";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();
</script><script async="async" src="https://www.googletagmanager.com/gtag/js?id=UA-159334016-1"></script><script>window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-159334016-1');
</script><link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Titillium+Web" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"search.xml","languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"简"},
  noticeOutdate: {"limitDay":90,"position":"top","messagePrev":"自上次更新以来已经","messageNext":"天，文章的内容可能已过时或存在差异。"},
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: {"limitCount":50000,"languages":{"author":"作者: Kylin","link":"链接: ","source":"来源: Kylin","info":"著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。"}},
  lightbox: 'fancybox',
  Snackbar: {"chs_to_cht":"你已切换为繁体","cht_to_chs":"你已切换为简体","day_to_night":"你已切换为深色模式","night_to_day":"你已切换为浅色模式","bgLight":"#FF0000","bgDark":"#2d3035","position":"bottom-left"},
  source: {
    jQuery: 'https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js',
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/js/jquery.justifiedGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/css/justifiedGallery.min.css'
    },
    fancybox: {
      js: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js',
      css: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: true,
  isanchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = { 
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2022-07-12 19:42:50'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          const isDarkMode = window.matchMedia('(prefers-color-scheme: dark)').matches
          const isLightMode = window.matchMedia('(prefers-color-scheme: light)').matches
          const isNotSpecified = window.matchMedia('(prefers-color-scheme: no-preference)').matches
          const hasNoSupport = !isDarkMode && !isLightMode && !isNotSpecified

          if (t === undefined) {
            if (isLightMode) activateLightMode()
            else if (isDarkMode) activateDarkMode()
            else if (isNotSpecified || hasNoSupport) {
              const now = new Date()
              const hour = now.getHours()
              const isNight = hour <= 6 || hour >= 18
              isNight ? activateDarkMode() : activateLightMode()
            }
            window.matchMedia('(prefers-color-scheme: dark)').addListener(function (e) {
              if (saveToLocal.get('theme') === undefined) {
                e.matches ? activateDarkMode() : activateLightMode()
              }
            })
          } else if (t === 'light') activateLightMode()
          else activateDarkMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const fontSizeVal = saveToLocal.get('global-font-size')
    if (fontSizeVal !== undefined) {
      document.documentElement.style.setProperty('--global-font-size', fontSizeVal + 'px')
    }
    })(window)</script><link rel="stylesheet" href="https://qiniu.codekylin.cn/github/img/img/custom.css"><link rel="stylesheet" href="//at.alicdn.com/t/font_1993646_z05rabxf05h.css"><link rel="stylesheet" href="https://qiniu.codekylin.cn/github/img/img/icon.css"><meta name="generator" content="Hexo 5.4.0"><link rel="alternate" href="/atom.xml" title="Kylin" type="application/atom+xml">
</head><body><div id="web_bg"></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="author-avatar"><img class="avatar-img" data-lazy-src="https://qiniu.codekylin.cn/img/20200807181526.jpg" onerror="onerror=null;src='https://qiniu.codekylin.cn/github/img/friend_404.gif'" alt="avatar"/></div><div class="site-data"><div class="data-item is-center"><div class="data-item-link"><a href="/archives/"><div class="headline">文章</div><div class="length-num">362</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/tags/"><div class="headline">标签</div><div class="length-num">427</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/categories/"><div class="headline">分类</div><div class="length-num">101</div></a></div></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fa fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fa fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fa fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fa fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fa fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fa fa-heart"></i><span> 关于</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://qiniu.codekylin.cn/github/img/img/wallhaven-5wqmj8.jpg')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">Kylin</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fa fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fa fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fa fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fa fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fa fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fa fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">Redis分布式锁</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2022-01-02T05:25:53.000Z" title="发表于 2022-01-02 13:25:53">2022-01-02</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2022-07-12T11:42:50.018Z" title="更新于 2022-07-12 19:42:50">2022-07-12</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/Redis/">Redis</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">4k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>17分钟</span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h2 id="环境搭建"><a href="#环境搭建" class="headerlink" title="环境搭建"></a>环境搭建</h2><h3 id="properties"><a href="#properties" class="headerlink" title="properties"></a>properties</h3><figure class="highlight properties"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">server.port</span>=<span class="string">1111</span></span><br><span class="line"><span class="meta">spring.redis.database</span>=<span class="string">0</span></span><br><span class="line"><span class="meta">spring.redis.host</span>=<span class="string">192.168.56.10</span></span><br><span class="line"><span class="meta">spring.redis.port</span>=<span class="string">6379</span></span><br><span class="line"><span class="comment">#连接池最大连接数（使用负值表示没有限制）默认8</span></span><br><span class="line"><span class="meta">spring.redis.lettuce.pool.max-active</span>=<span class="string">8</span></span><br><span class="line"><span class="comment">#连接池最大阻塞等待时间（使用负值表示没有限制）默认-1</span></span><br><span class="line"><span class="meta">spring.redis.lettuce.pool.max-wait</span>=<span class="string">-1</span></span><br><span class="line"><span class="comment">#连接池中的最大空闲连接默认8</span></span><br><span class="line"><span class="meta">spring.redis.lettuce.pool.max-idle</span>=<span class="string">8</span></span><br><span class="line"><span class="comment">#连接池中的最小空闲连接默认0</span></span><br><span class="line"><span class="meta">spring.redis.lettuce.pool.min-idle</span>=<span class="string">0</span></span><br></pre></td></tr></table></figure>

<p>redis的相关配置。</p>
<h3 id="pom-xml"><a href="#pom-xml" class="headerlink" title="pom.xml"></a>pom.xml</h3><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">           <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.boot<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">           <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-boot-starter-web<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">       <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line"></span><br><span class="line">       <span class="comment">&lt;!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-actuator --&gt;</span></span><br><span class="line">       <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">           <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.boot<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">           <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-boot-starter-actuator<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">       <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line"></span><br><span class="line">       <span class="comment">&lt;!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-redis --&gt;</span></span><br><span class="line">       <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">           <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.boot<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">           <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-boot-starter-data-redis<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">       <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line"></span><br><span class="line">       <span class="comment">&lt;!-- https://mvnrepository.com/artifact/org.apache.commons/commons-pool2 --&gt;</span></span><br><span class="line">       <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">           <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.apache.commons<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">           <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>commons-pool2<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">       <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line"></span><br><span class="line">       <span class="comment">&lt;!-- https://mvnrepository.com/artifact/redis.clients/jedis --&gt;</span></span><br><span class="line">       <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">           <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>redis.clients<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">           <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>jedis<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">           <span class="tag">&lt;<span class="name">version</span>&gt;</span>3.1.0<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">       <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line"></span><br><span class="line">       <span class="comment">&lt;!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-aop --&gt;</span></span><br><span class="line">       <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">           <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.boot<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">           <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-boot-starter-aop<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">       <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line"></span><br><span class="line">       </span><br><span class="line">       <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">           <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.boot<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">           <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-boot-devtools<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">           <span class="tag">&lt;<span class="name">scope</span>&gt;</span>runtime<span class="tag">&lt;/<span class="name">scope</span>&gt;</span></span><br><span class="line">           <span class="tag">&lt;<span class="name">optional</span>&gt;</span>true<span class="tag">&lt;/<span class="name">optional</span>&gt;</span></span><br><span class="line">       <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line"></span><br><span class="line">       <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">           <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.projectlombok<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">           <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>lombok<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">           <span class="tag">&lt;<span class="name">optional</span>&gt;</span>true<span class="tag">&lt;/<span class="name">optional</span>&gt;</span></span><br><span class="line">       <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">       <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">           <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>junit<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">           <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>junit<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">           <span class="tag">&lt;<span class="name">version</span>&gt;</span>4.12<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">       <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="config"><a href="#config" class="headerlink" title="config"></a>config</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> kylin</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">RedisConfig</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> RedisTemplate&lt;String, Serializable&gt; <span class="title">redisTemplate</span><span class="params">(LettuceConnectionFactory connectionFactory)</span> </span>&#123;</span><br><span class="line">        RedisTemplate&lt;String, Serializable&gt; redisTemplate = <span class="keyword">new</span> RedisTemplate&lt;&gt;();</span><br><span class="line"></span><br><span class="line">        <span class="comment">//序列化配置</span></span><br><span class="line">        redisTemplate.setKeySerializer(<span class="keyword">new</span> StringRedisSerializer());</span><br><span class="line">        redisTemplate.setValueSerializer(<span class="keyword">new</span> GenericJackson2JsonRedisSerializer());</span><br><span class="line">        redisTemplate.setConnectionFactory(connectionFactory);</span><br><span class="line">        <span class="keyword">return</span> redisTemplate;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>设置redis的key、value序列化配置。</p>
<h3 id="controller"><a href="#controller" class="headerlink" title="controller"></a>controller</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@RestController</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">GoodController</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    StringRedisTemplate stringRedisTemplate;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Value(&quot;$&#123;server.port&#125;&quot;)</span></span><br><span class="line">    <span class="keyword">private</span> String serverPort;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@GetMapping(&quot;/buyGoods&quot;)</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">buyGoods</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="comment">//get key 查看库存的数量够不够</span></span><br><span class="line">        String result = stringRedisTemplate.opsForValue().get(<span class="string">&quot;goods:001&quot;</span>);</span><br><span class="line">        <span class="keyword">int</span> goodsNumber = result == <span class="keyword">null</span> ? <span class="number">0</span> : Integer.parseInt(result);</span><br><span class="line">        <span class="keyword">if</span> (goodsNumber &gt; <span class="number">0</span>) &#123;</span><br><span class="line">            <span class="comment">//库存数量-1</span></span><br><span class="line">            <span class="keyword">int</span> realNumber = goodsNumber - <span class="number">1</span>;</span><br><span class="line">            stringRedisTemplate.opsForValue().set(<span class="string">&quot;goods:001&quot;</span>, String.valueOf(realNumber));</span><br><span class="line">            System.out.println(<span class="string">&quot;你已经成功秒杀商品，此时还剩余：&quot;</span> + realNumber + <span class="string">&quot;件&quot;</span> + <span class="string">&quot;\t 服务器端口: &quot;</span> + serverPort);</span><br><span class="line">            <span class="keyword">return</span> <span class="string">&quot;你已经成功秒杀商品，此时还剩余：&quot;</span> + realNumber + <span class="string">&quot;件&quot;</span> + <span class="string">&quot;\t 服务器端口: &quot;</span> + serverPort;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> <span class="string">&quot;商品已经售罄/活动结束/调用超时，欢迎下次光临&quot;</span> + <span class="string">&quot;\t 服务器端口: &quot;</span> + serverPort;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/image-20220102171549546.png" alt="image-20220102171549546"></p>
<p>创建两个redis项目，一个在端口<code>1111</code>运行，一个在<code>2222</code>运行。（redis记得启动）</p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/image-20220102171713356.png" alt="image-20220102171713356"></p>
<p>redis中给键名为<code>goods:001</code>设置值value为<code>100</code></p>
<p>启动项目访问<code>http://localhost:1111/buyGoods</code>和<code>http://localhost:3333/buyGoods</code></p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/image-20220102171855380.png" alt="image-20220102171855380"></p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/image-20220102171924317.png" alt="image-20220102171924317"></p>
<p>消费商品成功~</p>
<h2 id="1-0"><a href="#1-0" class="headerlink" title="1.0"></a>1.0</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@GetMapping(&quot;/buyGoods&quot;)</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> String <span class="title">buyGoods</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="comment">//get key 查看库存的数量够不够</span></span><br><span class="line">    String result = stringRedisTemplate.opsForValue().get(<span class="string">&quot;goods:001&quot;</span>);</span><br><span class="line">    <span class="keyword">int</span> goodsNumber = result == <span class="keyword">null</span> ? <span class="number">0</span> : Integer.parseInt(result);</span><br><span class="line">    <span class="keyword">if</span> (goodsNumber &gt; <span class="number">0</span>) &#123;</span><br><span class="line">        <span class="comment">//库存数量-1</span></span><br><span class="line">        <span class="keyword">int</span> realNumber = goodsNumber - <span class="number">1</span>;</span><br><span class="line">        stringRedisTemplate.opsForValue().set(<span class="string">&quot;goods:001&quot;</span>, String.valueOf(realNumber));</span><br><span class="line">        System.out.println(<span class="string">&quot;你已经成功秒杀商品，此时还剩余：&quot;</span> + realNumber + <span class="string">&quot;件&quot;</span> + <span class="string">&quot;\t 服务器端口: &quot;</span> + serverPort);</span><br><span class="line">        <span class="keyword">return</span> <span class="string">&quot;你已经成功秒杀商品，此时还剩余：&quot;</span> + realNumber + <span class="string">&quot;件&quot;</span> + <span class="string">&quot;\t 服务器端口: &quot;</span> + serverPort;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="string">&quot;商品已经售罄/活动结束/调用超时，欢迎下次光临&quot;</span> + <span class="string">&quot;\t 服务器端口: &quot;</span> + serverPort;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/image-20220102172303711.png" alt="image-20220102172303711"></p>
<p>此时这段代码，在一个线程是没有问题的，但是多线程下，则会出现各种问题，所以需要加锁。</p>
<h2 id="2-0（加锁）"><a href="#2-0（加锁）" class="headerlink" title="2.0（加锁）"></a>2.0（加锁）</h2><p>加锁的话我们是使用<code>synchronized</code>还是<code>lock</code>呢？？</p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/image-20220102172808173.png" alt="image-20220102172808173"></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@RestController</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">GoodController</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    StringRedisTemplate stringRedisTemplate;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Value(&quot;$&#123;server.port&#125;&quot;)</span></span><br><span class="line">    <span class="keyword">private</span> String serverPort;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@GetMapping(&quot;/buyGoods&quot;)</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">buyGoods</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">synchronized</span> (<span class="keyword">this</span>) &#123;</span><br><span class="line">            <span class="comment">//get key 查看库存的数量够不够</span></span><br><span class="line">            String result = stringRedisTemplate.opsForValue().get(<span class="string">&quot;goods:001&quot;</span>);</span><br><span class="line">            <span class="keyword">int</span> goodsNumber = result == <span class="keyword">null</span> ? <span class="number">0</span> : Integer.parseInt(result);</span><br><span class="line">            <span class="keyword">if</span> (goodsNumber &gt; <span class="number">0</span>) &#123;</span><br><span class="line">                <span class="comment">//库存数量-1</span></span><br><span class="line">                <span class="keyword">int</span> realNumber = goodsNumber - <span class="number">1</span>;</span><br><span class="line">                stringRedisTemplate.opsForValue().set(<span class="string">&quot;goods:001&quot;</span>, String.valueOf(realNumber));</span><br><span class="line">                System.out.println(<span class="string">&quot;你已经成功秒杀商品，此时还剩余：&quot;</span> + realNumber + <span class="string">&quot;件&quot;</span> + <span class="string">&quot;\t 服务器端口: &quot;</span> + serverPort);</span><br><span class="line">                <span class="keyword">return</span> <span class="string">&quot;你已经成功秒杀商品，此时还剩余：&quot;</span> + realNumber + <span class="string">&quot;件&quot;</span> + <span class="string">&quot;\t 服务器端口: &quot;</span> + serverPort;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">return</span> <span class="string">&quot;商品已经售罄/活动结束/调用超时，欢迎下次光临&quot;</span> + <span class="string">&quot;\t 服务器端口: &quot;</span> + serverPort;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>如果使用<code>synchronized</code>，像上图这样，虽然成功加锁，但是其他的请求线程则会一直停在这等待，锁的释放，请求会一直在转圈，造成线程的挤压。</p>
<p><code>synchronized</code>和<code>lock</code>的区别是在与业务。</p>
<ul>
<li>不见不散</li>
<li>过时不候</li>
</ul>
<p>lock可以设置尝试获取时间，超过了则做其他操作。</p>
<p>synchronized则一直等待。</p>
<p>所以我们可以使用<code>lock</code>的<code>tryLock()</code>方法，设置获取时间，超过了则做其他操作。</p>
<h3 id="配置nginx"><a href="#配置nginx" class="headerlink" title="配置nginx"></a>配置nginx</h3><p><a target="_blank" rel="noopener" href="https://www.cnblogs.com/saneri/p/11799865.html">docker部署nginx</a></p>
<p><code>docker run --name nginx -p 80:80 -d nginx</code></p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/image-20220102174638735.png" alt="image-20220102174638735"></p>
<p>将<code>incloude /etc/nginx/conf.d/*.conf</code>注释，否则会默认先加载这个文件下的conf配置。导致下面我们配的失效</p>
<p>访问<code>http://192.168.56.10/buyGoods/</code>则会负载均衡到本地启动的两个项目中</p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/image-20220102180001691.png" alt="image-20220102180001691"></p>
<p>此时我们访问<a target="_blank" rel="noopener" href="http://192.168.56.10/buyGoods/则会轮询消费1111和3333项目了。">http://192.168.56.10/buyGoods/则会轮询消费1111和3333项目了。</a></p>
<p>这样子我们这个单机版下好像解决了锁的问题（本地锁），但是分布式下是锁不住的，因为如果有10个这样的项目，每个项目同时都只有一个线程能运行，那么10个项目则会有10个线程去操作资源，这样还是多线程，会产生线程问题的！</p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20210813111420.png" alt="image-20210813111419751"></p>
<p>我们可以使用JMeter进行验证</p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/image-20220102180153695.png" alt="image-20220102180153695"></p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/image-20220102180330320.png" alt="image-20220102180330320"></p>
<p>点击运行之后，我们查看项目日志</p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/image-20220102180455302.png" alt="image-20220102180455302"></p>
<p>可以发现出现了多个商品，卖出去多次的情况，这样显然是不合理的！</p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/20210813143734.png" alt="image-20210813143732232"></p>
<p>所以我们则需要去一个统一的地方去管理，像redis、zookeeper、mysql</p>
<p>为了解决这种情况，我们则需要分布式锁，选择redis，也就是<code>redis分布式锁</code></p>
<h2 id="3-0（redis分布式锁）"><a href="#3-0（redis分布式锁）" class="headerlink" title="3.0（redis分布式锁）"></a>3.0（redis分布式锁）</h2><p>我们使用redis的<code>set</code>命令进行操作</p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/image-20220102181235578.png" alt="image-20220102181235578"></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"> <span class="keyword">public</span> <span class="keyword">final</span> String REDIS_LOCK = <span class="string">&quot;REDIS_LOCK&quot;</span>;  </span><br><span class="line">String value = UUID.randomUUID().toString() + Thread.currentThread().getName();</span><br><span class="line">        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(REDIS_LOCK, value);</span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> kylin</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@RestController</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">GoodController</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">final</span> String REDIS_LOCK = <span class="string">&quot;REDIS_LOCK&quot;</span>;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    StringRedisTemplate stringRedisTemplate;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="meta">@Value(&quot;$&#123;server.port&#125;&quot;)</span></span><br><span class="line">    <span class="keyword">private</span> String serverPort;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@GetMapping(&quot;/buyGoods&quot;)</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">buyGoods</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        String value = UUID.randomUUID().toString() + Thread.currentThread().getName();</span><br><span class="line">        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(REDIS_LOCK, value);</span><br><span class="line">        <span class="comment">//如果已经存在</span></span><br><span class="line">        <span class="keyword">if</span> (!flag) &#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="string">&quot;抢锁失败!&quot;</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">synchronized</span> (<span class="keyword">this</span>) &#123;</span><br><span class="line">            <span class="comment">//get key 查看库存的数量够不够</span></span><br><span class="line">            String result = stringRedisTemplate.opsForValue().get(<span class="string">&quot;goods:001&quot;</span>);</span><br><span class="line">            <span class="keyword">int</span> goodsNumber = result == <span class="keyword">null</span> ? <span class="number">0</span> : Integer.parseInt(result);</span><br><span class="line">            <span class="keyword">if</span> (goodsNumber &gt; <span class="number">0</span>) &#123;</span><br><span class="line">                <span class="comment">//库存数量-1</span></span><br><span class="line">                <span class="keyword">int</span> realNumber = goodsNumber - <span class="number">1</span>;</span><br><span class="line">                stringRedisTemplate.opsForValue().set(<span class="string">&quot;goods:001&quot;</span>, String.valueOf(realNumber));</span><br><span class="line">                System.out.println(<span class="string">&quot;你已经成功秒杀商品，此时还剩余：&quot;</span> + realNumber + <span class="string">&quot;件&quot;</span> + <span class="string">&quot;\t 服务器端口: &quot;</span> + serverPort);</span><br><span class="line">                <span class="comment">//解锁</span></span><br><span class="line">                stringRedisTemplate.delete(REDIS_LOCK);</span><br><span class="line">                <span class="keyword">return</span> <span class="string">&quot;你已经成功秒杀商品，此时还剩余：&quot;</span> + realNumber + <span class="string">&quot;件&quot;</span> + <span class="string">&quot;\t 服务器端口: &quot;</span> + serverPort;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> <span class="string">&quot;商品已经售罄/活动结束/调用超时，欢迎下次光临&quot;</span> + <span class="string">&quot;\t 服务器端口: &quot;</span> + serverPort;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>思路其实很简单，首先获取到锁的对象，会在reidis中创建一个键名为<code>REDIS_LOCK</code>的对象，给其设置一个随机值。随后进行操作资源，操作完成后在redis中删除该对象<code>stringRedisTemplate.delete(REDIS_LOCK);</code></p>
<p>而后面的线程也会进行其操作通过<code>setIfAbsent()</code>，只有redis中没有键名为<code>REDIS_LOCK</code>的对象时才能设置成功，如果redis中已经存在，说明已经有线程获取到了锁，并且没有释放。设置失败则return结束。</p>
<p>是否还有其他问题出现呢？？</p>
<p>加入获取锁的线程再运行中<strong>出现了异常</strong>，导致程序没有继续执行下去，从而没有把redis中的<code>REDIS_LOCK</code>给删除，那么后面的其他请求则都不会成功运行！</p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/image-20220102182359065.png" alt="image-20220102182359065"></p>
<h2 id="4-0（finaly）"><a href="#4-0（finaly）" class="headerlink" title="4.0（finaly）"></a>4.0（finaly）</h2><p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/image-20220102182522902.png" alt="image-20220102182522902"></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> kylin</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@RestController</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">GoodController</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">final</span> String REDIS_LOCK = <span class="string">&quot;REDIS_LOCK&quot;</span>;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    StringRedisTemplate stringRedisTemplate;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="meta">@Value(&quot;$&#123;server.port&#125;&quot;)</span></span><br><span class="line">    <span class="keyword">private</span> String serverPort;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@GetMapping(&quot;/buyGoods&quot;)</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">buyGoods</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            String value = UUID.randomUUID().toString() + Thread.currentThread().getName();</span><br><span class="line">            Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(REDIS_LOCK, value);</span><br><span class="line">            <span class="comment">//如果已经存在</span></span><br><span class="line">            <span class="keyword">if</span> (!flag) &#123;</span><br><span class="line">                <span class="keyword">return</span> <span class="string">&quot;抢锁失败!&quot;</span>;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">synchronized</span> (<span class="keyword">this</span>) &#123;</span><br><span class="line">                <span class="comment">//get key 查看库存的数量够不够</span></span><br><span class="line">                String result = stringRedisTemplate.opsForValue().get(<span class="string">&quot;goods:001&quot;</span>);</span><br><span class="line">                <span class="keyword">int</span> goodsNumber = result == <span class="keyword">null</span> ? <span class="number">0</span> : Integer.parseInt(result);</span><br><span class="line">                <span class="keyword">if</span> (goodsNumber &gt; <span class="number">0</span>) &#123;</span><br><span class="line">                    <span class="comment">//库存数量-1</span></span><br><span class="line">                    <span class="keyword">int</span> realNumber = goodsNumber - <span class="number">1</span>;</span><br><span class="line">                    stringRedisTemplate.opsForValue().set(<span class="string">&quot;goods:001&quot;</span>, String.valueOf(realNumber));</span><br><span class="line">                    System.out.println(<span class="string">&quot;你已经成功秒杀商品，此时还剩余：&quot;</span> + realNumber + <span class="string">&quot;件&quot;</span> + <span class="string">&quot;\t 服务器端口: &quot;</span> + serverPort);</span><br><span class="line"></span><br><span class="line">                    <span class="keyword">return</span> <span class="string">&quot;你已经成功秒杀商品，此时还剩余：&quot;</span> + realNumber + <span class="string">&quot;件&quot;</span> + <span class="string">&quot;\t 服务器端口: &quot;</span> + serverPort;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">return</span> <span class="string">&quot;商品已经售罄/活动结束/调用超时，欢迎下次光临&quot;</span> + <span class="string">&quot;\t 服务器端口: &quot;</span> + serverPort;</span><br><span class="line">        &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">            <span class="comment">//解锁</span></span><br><span class="line">            stringRedisTemplate.delete(REDIS_LOCK);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>将从redis删除对象的操作写在finally代码快中，保证最后一定能释放。</p>
<p>（使用的是synchronized出现异常，jvm会自动释放锁，如果使用的是Lock，则还需要在finally代码快中加入unlock操作释放锁）</p>
<p>是否还存在着问题呢？？？</p>
<p>上面我们假设的是程序出现异常，但是如果我们这个项目突然<strong>宕机</strong>了呢？</p>
<p>例如部署了微服务jar包的机器挂了，代码层面根本没有走到finally这块，就没办法保证解锁，这个key没有被删除，所以我们需要给key设置过期时间</p>
<h2 id="5-0（key过期时间）"><a href="#5-0（key过期时间）" class="headerlink" title="5.0（key过期时间）"></a>5.0（key过期时间）</h2><p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/image-20220102183241190.png" alt="image-20220102183241190"></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> kylin</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@RestController</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">GoodController</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">final</span> String REDIS_LOCK = <span class="string">&quot;REDIS_LOCK&quot;</span>;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    StringRedisTemplate stringRedisTemplate;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="meta">@Value(&quot;$&#123;server.port&#125;&quot;)</span></span><br><span class="line">    <span class="keyword">private</span> String serverPort;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@GetMapping(&quot;/buyGoods&quot;)</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">buyGoods</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            String value = UUID.randomUUID().toString() + Thread.currentThread().getName();</span><br><span class="line">            Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(REDIS_LOCK, value);</span><br><span class="line">            <span class="comment">//redis设置过期时间</span></span><br><span class="line">            stringRedisTemplate.expire(REDIS_LOCK, <span class="number">10L</span>, TimeUnit.SECONDS);</span><br><span class="line">            <span class="comment">//如果已经存在</span></span><br><span class="line">            <span class="keyword">if</span> (!flag) &#123;</span><br><span class="line">                <span class="keyword">return</span> <span class="string">&quot;抢锁失败!&quot;</span>;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">synchronized</span> (<span class="keyword">this</span>) &#123;</span><br><span class="line">                <span class="comment">//get key 查看库存的数量够不够</span></span><br><span class="line">                String result = stringRedisTemplate.opsForValue().get(<span class="string">&quot;goods:001&quot;</span>);</span><br><span class="line">                <span class="keyword">int</span> goodsNumber = result == <span class="keyword">null</span> ? <span class="number">0</span> : Integer.parseInt(result);</span><br><span class="line">                <span class="keyword">if</span> (goodsNumber &gt; <span class="number">0</span>) &#123;</span><br><span class="line">                    <span class="comment">//库存数量-1</span></span><br><span class="line">                    <span class="keyword">int</span> realNumber = goodsNumber - <span class="number">1</span>;</span><br><span class="line">                    stringRedisTemplate.opsForValue().set(<span class="string">&quot;goods:001&quot;</span>, String.valueOf(realNumber));</span><br><span class="line">                    System.out.println(<span class="string">&quot;你已经成功秒杀商品，此时还剩余：&quot;</span> + realNumber + <span class="string">&quot;件&quot;</span> + <span class="string">&quot;\t 服务器端口: &quot;</span> + serverPort);</span><br><span class="line"></span><br><span class="line">                    <span class="keyword">return</span> <span class="string">&quot;你已经成功秒杀商品，此时还剩余：&quot;</span> + realNumber + <span class="string">&quot;件&quot;</span> + <span class="string">&quot;\t 服务器端口: &quot;</span> + serverPort;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">return</span> <span class="string">&quot;商品已经售罄/活动结束/调用超时，欢迎下次光临&quot;</span> + <span class="string">&quot;\t 服务器端口: &quot;</span> + serverPort;</span><br><span class="line">        &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">            <span class="comment">//解锁</span></span><br><span class="line">            stringRedisTemplate.delete(REDIS_LOCK);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><code>stringRedisTemplate.expire(REDIS_LOCK, 10L, TimeUnit.SECONDS);</code></p>
<p>但是这样设置key+过期时间分开了，必须要合并成一行具备原子性。</p>
<p>否则同样创建为key，项目宕机，同样key不会删除。我们必选要保证创建key和设置key过期时间是原子操作，必须同时成功！</p>
<h2 id="6-0（key原子性）"><a href="#6-0（key原子性）" class="headerlink" title="6.0（key原子性）"></a>6.0（key原子性）</h2><p><code>Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(REDIS_LOCK, value, 10L, TimeUnit.SECONDS);</code></p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/image-20220102183819645.png" alt="image-20220102183819645"></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> kylin</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@RestController</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">GoodController</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">final</span> String REDIS_LOCK = <span class="string">&quot;REDIS_LOCK&quot;</span>;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    StringRedisTemplate stringRedisTemplate;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="meta">@Value(&quot;$&#123;server.port&#125;&quot;)</span></span><br><span class="line">    <span class="keyword">private</span> String serverPort;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@GetMapping(&quot;/buyGoods&quot;)</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">buyGoods</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            String value = UUID.randomUUID().toString() + Thread.currentThread().getName();</span><br><span class="line">            Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(REDIS_LOCK, value, <span class="number">10L</span>, TimeUnit.SECONDS);</span><br><span class="line">            <span class="comment">//如果已经存在</span></span><br><span class="line">            <span class="keyword">if</span> (!flag) &#123;</span><br><span class="line">                <span class="keyword">return</span> <span class="string">&quot;抢锁失败!&quot;</span>;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">synchronized</span> (<span class="keyword">this</span>) &#123;</span><br><span class="line">                <span class="comment">//get key 查看库存的数量够不够</span></span><br><span class="line">                String result = stringRedisTemplate.opsForValue().get(<span class="string">&quot;goods:001&quot;</span>);</span><br><span class="line">                <span class="keyword">int</span> goodsNumber = result == <span class="keyword">null</span> ? <span class="number">0</span> : Integer.parseInt(result);</span><br><span class="line">                <span class="keyword">if</span> (goodsNumber &gt; <span class="number">0</span>) &#123;</span><br><span class="line">                    <span class="comment">//库存数量-1</span></span><br><span class="line">                    <span class="keyword">int</span> realNumber = goodsNumber - <span class="number">1</span>;</span><br><span class="line">                    stringRedisTemplate.opsForValue().set(<span class="string">&quot;goods:001&quot;</span>, String.valueOf(realNumber));</span><br><span class="line">                    System.out.println(<span class="string">&quot;你已经成功秒杀商品，此时还剩余：&quot;</span> + realNumber + <span class="string">&quot;件&quot;</span> + <span class="string">&quot;\t 服务器端口: &quot;</span> + serverPort);</span><br><span class="line"></span><br><span class="line">                    <span class="keyword">return</span> <span class="string">&quot;你已经成功秒杀商品，此时还剩余：&quot;</span> + realNumber + <span class="string">&quot;件&quot;</span> + <span class="string">&quot;\t 服务器端口: &quot;</span> + serverPort;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">return</span> <span class="string">&quot;商品已经售罄/活动结束/调用超时，欢迎下次光临&quot;</span> + <span class="string">&quot;\t 服务器端口: &quot;</span> + serverPort;</span><br><span class="line">        &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">            <span class="comment">//解锁</span></span><br><span class="line">            stringRedisTemplate.delete(REDIS_LOCK);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>不过还是会存在问题….</p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/image-20220102184355346.png" alt="image-20220102184355346"></p>
<p>假如A线程再设置的10秒钟内没有执行完业务，key被删除后，另一个线程B就能成功设置key，再等待A线程释放锁（等待synchronized代码快外）。A线程执行业务完成后，执行删除key，但是这个key其实不是他创建的key，是B创建的key，A创建的key已经因为到期自动删除了。</p>
<h2 id="7-0（超时业务-删自己的key）"><a href="#7-0（超时业务-删自己的key）" class="headerlink" title="7.0（超时业务 删自己的key）"></a>7.0（超时业务 删自己的key）</h2><p>所以我们要在删key操作中做判断，判断值是否相等，从而保证在过期时间内只能自己删除自己的key。</p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/image-20220102184912481.png" alt="image-20220102184912481"></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">if</span> (stringRedisTemplate.opsForValue().get(REDIS_LOCK).equalsIgnoreCase(value)) &#123;</span><br><span class="line">     <span class="comment">//解锁</span></span><br><span class="line">          stringRedisTemplate.delete(REDIS_LOCK);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>不过还是有原子性的问题，if判断和删除key操作不是原子性的！</p>
<p>如果判断成功，程序宕机，还是不能删除掉key。所以我们要保证只要进行了value值判断，相同就一定会进行删除key的操作。</p>
<h2 id="8-0（删除key原子性）"><a href="#8-0（删除key原子性）" class="headerlink" title="8.0（删除key原子性）"></a>8.0（删除key原子性）</h2><p>使用<code>lua</code>脚本</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Redis工具类</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> kylin</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">RedisUtils</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> JedisPool jedisPool;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">static</span> &#123;</span><br><span class="line">        JedisPoolConfig jedisPoolConfig = <span class="keyword">new</span> JedisPoolConfig();</span><br><span class="line">        jedisPoolConfig.setMaxTotal(<span class="number">20</span>);</span><br><span class="line">        jedisPoolConfig.setMaxIdle(<span class="number">10</span>);</span><br><span class="line"></span><br><span class="line">        jedisPool = <span class="keyword">new</span> JedisPool(jedisPoolConfig, <span class="string">&quot;192.168.56.10&quot;</span>, <span class="number">6379</span>, <span class="number">100000</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> Jedis <span class="title">getJedis</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> (<span class="keyword">null</span> != jedisPool) &#123;</span><br><span class="line">            <span class="keyword">return</span> jedisPool.getResource();</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> Exception(<span class="string">&quot;Jedispool is not ok&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/image-20220103173958750.png" alt="image-20220103173958750"></p>
<p>不过还是有问题~</p>
<p>我们要确保redisLock过期时间大于业务执行时间的问题，Redis分布式锁如何续期？</p>
<p>还有就是Redis集群环境下，Redis是保证<code>AP</code>，就会出现redis异步复制造成锁的丢失。</p>
<p>例如：主节点没来的及把刚刚set进来的这条数据给从节点，就挂了。。</p>
<h2 id="9-0（redisson）"><a href="#9-0（redisson）" class="headerlink" title="9.0（redisson）"></a>9.0（redisson）</h2><p>导入依赖</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!-- https://mvnrepository.com/artifact/org.redisson/redisson --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.redisson<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>redisson<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">version</span>&gt;</span>3.13.4<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/image-20220103183219217.png" alt="image-20220103183219217"></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> kylin</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">RedisConfig</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> RedisTemplate&lt;String, Serializable&gt; <span class="title">redisTemplate</span><span class="params">(LettuceConnectionFactory connectionFactory)</span> </span>&#123;</span><br><span class="line">        RedisTemplate&lt;String, Serializable&gt; redisTemplate = <span class="keyword">new</span> RedisTemplate&lt;&gt;();</span><br><span class="line"></span><br><span class="line">        <span class="comment">//序列化配置</span></span><br><span class="line">        redisTemplate.setKeySerializer(<span class="keyword">new</span> StringRedisSerializer());</span><br><span class="line">        redisTemplate.setValueSerializer(<span class="keyword">new</span> GenericJackson2JsonRedisSerializer());</span><br><span class="line">        redisTemplate.setConnectionFactory(connectionFactory);</span><br><span class="line">        <span class="keyword">return</span> redisTemplate;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Redisson <span class="title">redisson</span><span class="params">()</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">        Config config = <span class="keyword">new</span> Config();</span><br><span class="line">        config.useSingleServer().setAddress(<span class="string">&quot;redis://192.168.56.10:6379&quot;</span>).setDatabase(<span class="number">0</span>);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> (Redisson) Redisson.create(config);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>配置注入Redisson</p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/image-20220103183449535.png" alt="image-20220103183449535"></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> kylin</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@RestController</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">GoodController</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">final</span> String REDIS_LOCK = <span class="string">&quot;REDIS_LOCK&quot;</span>;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    StringRedisTemplate stringRedisTemplate;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    Redisson redisson;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="meta">@Value(&quot;$&#123;server.port&#125;&quot;)</span></span><br><span class="line">    <span class="keyword">private</span> String serverPort;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@GetMapping(&quot;/buyGoods&quot;)</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">buyGoods</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        String value = UUID.randomUUID().toString() + Thread.currentThread().getName();</span><br><span class="line">        RLock redissonLock = redisson.getLock(REDIS_LOCK);</span><br><span class="line">        redissonLock.lock();</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="comment">//get key 查看库存的数量够不够</span></span><br><span class="line">            String result = stringRedisTemplate.opsForValue().get(<span class="string">&quot;goods:001&quot;</span>);</span><br><span class="line">            <span class="keyword">int</span> goodsNumber = result == <span class="keyword">null</span> ? <span class="number">0</span> : Integer.parseInt(result);</span><br><span class="line">            <span class="keyword">if</span> (goodsNumber &gt; <span class="number">0</span>) &#123;</span><br><span class="line">                <span class="comment">//库存数量-1</span></span><br><span class="line">                <span class="keyword">int</span> realNumber = goodsNumber - <span class="number">1</span>;</span><br><span class="line">                stringRedisTemplate.opsForValue().set(<span class="string">&quot;goods:001&quot;</span>, String.valueOf(realNumber));</span><br><span class="line">                System.out.println(<span class="string">&quot;你已经成功秒杀商品，此时还剩余：&quot;</span> + realNumber + <span class="string">&quot;件&quot;</span> + <span class="string">&quot;\t 服务器端口: &quot;</span> + serverPort);</span><br><span class="line"></span><br><span class="line">                <span class="keyword">return</span> <span class="string">&quot;你已经成功秒杀商品，此时还剩余：&quot;</span> + realNumber + <span class="string">&quot;件&quot;</span> + <span class="string">&quot;\t 服务器端口: &quot;</span> + serverPort;</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="keyword">return</span> <span class="string">&quot;商品已经售罄/活动结束/调用超时，欢迎下次光临&quot;</span> + <span class="string">&quot;\t 服务器端口: &quot;</span> + serverPort;</span><br><span class="line">        &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">            redissonLock.unlock();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>简单方便了好多。。。还强大~~</p>
<p>压测请求100之后，非常和谐…</p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/image-20220103184053412.png" alt="image-20220103184053412"></p>
<p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/image-20220103184004965.png" alt="image-20220103184004965"></p>
<p>不过还是可能出现以上异常，也就是<strong>当前解锁线程不是锁的持有线程</strong></p>
<h3 id="9-1"><a href="#9-1" class="headerlink" title="9.1"></a>9.1</h3><p><img src= "https://gitee.com/kylincw/images/raw/master/loading.gif" data-lazy-src="https://qiniu.codekylin.cn/img/image-20220103184345129.png" alt="image-20220103184345129"></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> kylin</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@RestController</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">GoodController</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">final</span> String REDIS_LOCK = <span class="string">&quot;REDIS_LOCK&quot;</span>;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    StringRedisTemplate stringRedisTemplate;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    Redisson redisson;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="meta">@Value(&quot;$&#123;server.port&#125;&quot;)</span></span><br><span class="line">    <span class="keyword">private</span> String serverPort;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@GetMapping(&quot;/buyGoods&quot;)</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">buyGoods</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        String value = UUID.randomUUID().toString() + Thread.currentThread().getName();</span><br><span class="line">        RLock redissonLock = redisson.getLock(REDIS_LOCK);</span><br><span class="line">        redissonLock.lock();</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="comment">//get key 查看库存的数量够不够</span></span><br><span class="line">            String result = stringRedisTemplate.opsForValue().get(<span class="string">&quot;goods:001&quot;</span>);</span><br><span class="line">            <span class="keyword">int</span> goodsNumber = result == <span class="keyword">null</span> ? <span class="number">0</span> : Integer.parseInt(result);</span><br><span class="line">            <span class="keyword">if</span> (goodsNumber &gt; <span class="number">0</span>) &#123;</span><br><span class="line">                <span class="comment">//库存数量-1</span></span><br><span class="line">                <span class="keyword">int</span> realNumber = goodsNumber - <span class="number">1</span>;</span><br><span class="line">                stringRedisTemplate.opsForValue().set(<span class="string">&quot;goods:001&quot;</span>, String.valueOf(realNumber));</span><br><span class="line">                System.out.println(<span class="string">&quot;你已经成功秒杀商品，此时还剩余：&quot;</span> + realNumber + <span class="string">&quot;件&quot;</span> + <span class="string">&quot;\t 服务器端口: &quot;</span> + serverPort);</span><br><span class="line"></span><br><span class="line">                <span class="keyword">return</span> <span class="string">&quot;你已经成功秒杀商品，此时还剩余：&quot;</span> + realNumber + <span class="string">&quot;件&quot;</span> + <span class="string">&quot;\t 服务器端口: &quot;</span> + serverPort;</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="keyword">return</span> <span class="string">&quot;商品已经售罄/活动结束/调用超时，欢迎下次光临&quot;</span> + <span class="string">&quot;\t 服务器端口: &quot;</span> + serverPort;</span><br><span class="line">        &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">            <span class="keyword">if</span> (redissonLock.isLocked())&#123;</span><br><span class="line">                <span class="keyword">if</span> (redissonLock.isHeldByCurrentThread())&#123;</span><br><span class="line">                    redissonLock.unlock();</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li><code>redissonLock.isLocked()</code>redis是否上锁</li>
<li><code>redissonLock.isHeldByCurrentThread()</code>当前线程是否是锁的持有线程</li>
</ul>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">Kylin</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://www.codekylin.cn/64631.html">https://www.codekylin.cn/64631.html</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://www.codekylin.cn" target="_blank">Kylin</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/Redis/">Redis</a><a class="post-meta__tags" href="/tags/%E5%88%86%E5%B8%83%E5%BC%8F%E9%94%81/">分布式锁</a></div><div class="post_share"><div class="social-share" data-image="https://qiniu.codekylin.cn/github/img/img/wallhaven-5wqmj8.jpg" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/social-share.js/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/social-share.js/dist/js/social-share.min.js" defer></script></div></div><div class="post-reward"><div class="reward-button button--animated"><i class="fas fa-qrcode"></i> 打赏</div><div class="reward-main"><ul class="reward-all"><li class="reward-item"><a href="https://qiniu.codekylin.cn/img/20200807181442.jpg" target="_blank"><img class="post-qr-code-img" data-lazy-src="https://qiniu.codekylin.cn/img/20200807181442.jpg" alt="微信"/></a><div class="post-qr-code-desc">微信</div></li><li class="reward-item"><a href="https://qiniu.codekylin.cn/img/20200807181505.jpg" target="_blank"><img class="post-qr-code-img" data-lazy-src="https://qiniu.codekylin.cn/img/20200807181505.jpg" alt="支付寶"/></a><div class="post-qr-code-desc">支付寶</div></li></ul></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/40200.html"><img class="prev-cover" data-lazy-src="https://qiniu.codekylin.cn/github/img/img/wallhaven-6qvvrx.jpg" onerror="onerror=null;src='/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">谷粒商城记录</div></div></a></div><div class="next-post pull-right"><a href="/59732.html"><img class="next-cover" data-lazy-src="https://qiniu.codekylin.cn/github/img/img/博客封面14.png" onerror="onerror=null;src='/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">AQS抽象的队列同步器</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span> 相关推荐</span></div><div class="relatedPosts-list"><div><a href="/34748.html" title="Redis三大特殊类型和事务"><img class="cover" data-lazy-src="https://qiniu.codekylin.cn/github/img/img/wallhaven-j5jyjp.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-04-26</div><div class="title">Redis三大特殊类型和事务</div></div></a></div><div><a href="/53469.html" title="Redis主从复制"><img class="cover" data-lazy-src="https://qiniu.codekylin.cn/github/img/img/博客封面1.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-05-03</div><div class="title">Redis主从复制</div></div></a></div><div><a href="/30313.html" title="Redis发布订阅"><img class="cover" data-lazy-src="https://qiniu.codekylin.cn/github/img/img/wallhaven-492lkw.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-05-03</div><div class="title">Redis发布订阅</div></div></a></div><div><a href="/54932.html" title="Redis哨兵模式"><img class="cover" data-lazy-src="https://qiniu.codekylin.cn/github/img/img/wallhaven-oxm7vp.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-05-04</div><div class="title">Redis哨兵模式</div></div></a></div><div><a href="/62112.html" title="Redis持久化"><img class="cover" data-lazy-src="https://qiniu.codekylin.cn/github/images/20200505210116.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-05-03</div><div class="title">Redis持久化</div></div></a></div><div><a href="/64507.html" title="Redis的入门与安装"><img class="cover" data-lazy-src="https://qiniu.codekylin.cn/github/img/img20200824151815.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-04-23</div><div class="title">Redis的入门与安装</div></div></a></div></div></div><hr/><div id="post-comment"><div class="comment-head"><div class="comment-headline"><i class="fas fa-comments fa-fw"></i><span> 评论</span></div></div><div class="comment-wrap"><div><div class="vcomment" id="vcomment"></div></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="card-info-avatar is-center"><img class="avatar-img" data-lazy-src="https://qiniu.codekylin.cn/img/20200807181526.jpg" onerror="this.onerror=null;this.src='https://qiniu.codekylin.cn/github/img/friend_404.gif'" alt="avatar"/><div class="author-info__name">Kylin</div><div class="author-info__description">学习不易，努力努力~</div></div><div class="card-info-data"><div class="card-info-data-item is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">362</div></a></div><div class="card-info-data-item is-center"><a href="/tags/"><div class="headline">标签</div><div class="length-num">427</div></a></div><div class="card-info-data-item is-center"><a href="/categories/"><div class="headline">分类</div><div class="length-num">101</div></a></div></div><a class="button--animated" id="card-info-btn"><i class="fas fa-bookmark"></i><span>加入书签</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://github.com/kylincw" target="_blank" title="Github"><i class="iconfont icon-github"></i></a><a class="social-icon" href="tencent://message/?Menu=yes&amp;uin=171346168&amp;Service=300&amp;sigT=45a1e5847943b64c6ff3990f8a9e644d2b31356cb0b4ac6b24663a3c8dd0f8aa12a595b1714f9d45" target="_blank" title="qq"><i class="iconfont icon-qq"></i></a><a class="social-icon" href="https://space.bilibili.com/53836035" target="_blank" title="BiliBili"><i class="iconfont icon-bilibili-line"></i></a><a class="social-icon" href="mailto:zhang171346168@qq.com" target="_blank" title="Email"><i class="iconfont icon-email1"></i></a><a class="social-icon" href="/atom.xml" target="_blank" title="RSS"><i class="iconfont icon-rss"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn card-announcement-animation"></i><span>公告</span></div><div class="announcement_content">学习不易，努力努力！</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%8E%AF%E5%A2%83%E6%90%AD%E5%BB%BA"><span class="toc-number">1.</span> <span class="toc-text">环境搭建</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#properties"><span class="toc-number">1.1.</span> <span class="toc-text">properties</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#pom-xml"><span class="toc-number">1.2.</span> <span class="toc-text">pom.xml</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#config"><span class="toc-number">1.3.</span> <span class="toc-text">config</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#controller"><span class="toc-number">1.4.</span> <span class="toc-text">controller</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#1-0"><span class="toc-number">2.</span> <span class="toc-text">1.0</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#2-0%EF%BC%88%E5%8A%A0%E9%94%81%EF%BC%89"><span class="toc-number">3.</span> <span class="toc-text">2.0（加锁）</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E9%85%8D%E7%BD%AEnginx"><span class="toc-number">3.1.</span> <span class="toc-text">配置nginx</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#3-0%EF%BC%88redis%E5%88%86%E5%B8%83%E5%BC%8F%E9%94%81%EF%BC%89"><span class="toc-number">4.</span> <span class="toc-text">3.0（redis分布式锁）</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#4-0%EF%BC%88finaly%EF%BC%89"><span class="toc-number">5.</span> <span class="toc-text">4.0（finaly）</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#5-0%EF%BC%88key%E8%BF%87%E6%9C%9F%E6%97%B6%E9%97%B4%EF%BC%89"><span class="toc-number">6.</span> <span class="toc-text">5.0（key过期时间）</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#6-0%EF%BC%88key%E5%8E%9F%E5%AD%90%E6%80%A7%EF%BC%89"><span class="toc-number">7.</span> <span class="toc-text">6.0（key原子性）</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#7-0%EF%BC%88%E8%B6%85%E6%97%B6%E4%B8%9A%E5%8A%A1-%E5%88%A0%E8%87%AA%E5%B7%B1%E7%9A%84key%EF%BC%89"><span class="toc-number">8.</span> <span class="toc-text">7.0（超时业务 删自己的key）</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#8-0%EF%BC%88%E5%88%A0%E9%99%A4key%E5%8E%9F%E5%AD%90%E6%80%A7%EF%BC%89"><span class="toc-number">9.</span> <span class="toc-text">8.0（删除key原子性）</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#9-0%EF%BC%88redisson%EF%BC%89"><span class="toc-number">10.</span> <span class="toc-text">9.0（redisson）</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#9-1"><span class="toc-number">10.1.</span> <span class="toc-text">9.1</span></a></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/56352.html" title="be动词"><img data-lazy-src="https://qiniu.codekylin.cn/github/img/img/博客封面10.png" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="be动词"/></a><div class="content"><a class="title" href="/56352.html" title="be动词">be动词</a><time datetime="2022-07-12T11:47:29.800Z" title="更新于 2022-07-12 19:47:29">2022-07-12</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/36436.html" title="JVM堆内存"><img data-lazy-src="https://qiniu.codekylin.cn/img/20200418115059.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="JVM堆内存"/></a><div class="content"><a class="title" href="/36436.html" title="JVM堆内存">JVM堆内存</a><time datetime="2022-07-12T11:47:29.800Z" title="更新于 2022-07-12 19:47:29">2022-07-12</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/44292.html" title="Java多线程详解"><img data-lazy-src="https://qiniu.codekylin.cn/github/img/img/wallhaven-eorjzk.png" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Java多线程详解"/></a><div class="content"><a class="title" href="/44292.html" title="Java多线程详解">Java多线程详解</a><time datetime="2022-07-12T11:47:29.800Z" title="更新于 2022-07-12 19:47:29">2022-07-12</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/40200.html" title="谷粒商城记录"><img data-lazy-src="https://qiniu.codekylin.cn/github/img/img/wallhaven-6qvvrx.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="谷粒商城记录"/></a><div class="content"><a class="title" href="/40200.html" title="谷粒商城记录">谷粒商城记录</a><time datetime="2022-07-12T11:47:29.800Z" title="更新于 2022-07-12 19:47:29">2022-07-12</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/27082.html" title="Spring学习-3"><img data-lazy-src="https://qiniu.codekylin.cn/github/img/img/wallhaven-4x28xo.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Spring学习-3"/></a><div class="content"><a class="title" href="/27082.html" title="Spring学习-3">Spring学习-3</a><time datetime="2022-07-12T11:47:29.799Z" title="更新于 2022-07-12 19:47:29">2022-07-12</time></div></div></div></div></div></div></main><footer id="footer" style="background-image: url('https://qiniu.codekylin.cn/github/img/img/wallhaven-5wqmj8.jpg')"><div id="footer-wrap"><div class="copyright">&copy;2019 - 2022 By Kylin</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div><div class="footer_custom_text"><a target="_blank" rel="noopener" href="https://beian.miit.gov.cn/"><img class="icp-icon" src="https://img.alicdn.com/tfs/TB1..50QpXXXXX7XpXXXXXXXXXX-40-40.png"><span>湘ICP备2022005420号-1</span></a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="font-plus" type="button" title="放大字体"><i class="fas fa-plus"></i></button><button id="font-minus" type="button" title="缩小字体"><i class="fas fa-minus"></i></button><button id="translateLink" type="button" title="简繁转换">繁</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><a id="to_comment" href="#post-comment" title="直达评论"><i class="fas fa-comments"></i></a><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="local-search"><div class="search-dialog"><div class="search-dialog__title" id="local-search-title">本地搜索</div><div id="local-input-panel"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div></div><hr/><div id="local-search-results"></div><span class="search-close-button"><i class="fas fa-times"></i></span></div><div id="search-mask"></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="/js/tw_cn.js"></script><script src="https://cdn.jsdelivr.net/npm/instant.page/instantpage.min.js" type="module"></script><script src="https://cdn.jsdelivr.net/npm/vanilla-lazyload/dist/lazyload.iife.min.js"></script><script src="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.js"></script><script src="/js/search/local-search.js"></script><div class="js-pjax"><script>function loadValine () {
  function initValine () {
    const valine = new Valine(Object.assign({
      el: '#vcomment',
      appId: 'ClIyIUhj1ue2rcRTsApYCR50-gzGzoHsz',
      appKey: 'ATug9IScYQBHILhKWEqBHYxM',
      placeholder: '昵称填入QQ号能获取到QQ头像哦~请输入正确的邮箱地址，你将会快速收到我的回复并且通过邮件通知你！~',
      avatar: 'robohash',
      meta: 'nick,mail,link'.split(','),
      pageSize: '10',
      lang: 'zh-cn',
      recordIP: false,
      serverURLs: 'https://cliyiuhj.lc-cn-n1-shared.com',
      emojiCDN: '',
      emojiMaps: "",
      enableQQ: true,
      path: window.location.pathname,
      requiredFields: ["nick,mail"],
      visitor: false
    }, null))
  }

  if (typeof Valine === 'function') initValine() 
  else getScript('https://cdn.jsdelivr.net/npm/valine/dist/Valine.min.js').then(initValine)
}

if ('Valine' === 'Valine' || !true) {
  if (true) btf.loadComment(document.getElementById('vcomment'),loadValine)
  else setTimeout(loadValine, 0)
} else {
  function loadOtherComment () {
    loadValine()
  }
}</script></div><script defer="defer" id="ribbon" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/canvas-ribbon.min.js" size="150" alpha="0.6" zIndex="-1" mobile="false" data-click="true"></script><script defer="defer" id="fluttering_ribbon" mobile="false" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/canvas-fluttering-ribbon.min.js"></script></div></body></html>